﻿using AntdUI;
using Super.Admin.Global;
using Super.Admin.Utils.ThemeManager;
using Super.Admin.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Super.Admin.Utils.EventAggregator.EventType;
using Super.Admin.Utils.EventAggregator;
using Super.Admin.IServices;
using Super.Admin.Entities;
using Super.Admin.Services;
using Super.Admin.Models.User;
using Super.Admin.Mappers;
using Super.Admin.Models.Role;
using Super.Admin.Models.Department;
using System.Runtime.Intrinsics.Arm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Super.Admin.Models.Permission;
using System.Security.Policy;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Super.Admin.Views.Page
{
    public partial class UserManagementModify : UserControl
    {
        private readonly IUserService _userService;
        private readonly IUserOperateLogService _userOperateLogService;
        private UserDetatilModel _userModel;
        private List<RoleBaseModel> _roleModels;
        private List<DepartmentDetailModel> _departmentModels;
        private Form _form;
        public UserManagementModify(Form form, UserDetatilModel userModel, List<RoleBaseModel> roleModels, List<DepartmentDetailModel> depaetmentModels, IUserService userService, IUserOperateLogService userOperateLogService,string title)
        {
            InitializeComponent();
            _form = form;
            _userModel = userModel;
            _departmentModels = depaetmentModels;
            _roleModels = roleModels;
            _userService = userService;
            _userOperateLogService = userOperateLogService;
            LblTitle.Text = title;
            this.Load += UcUserManagementModify_Load;
        }

        private string imagePath;

        private void UcUserManagementModify_Load(object? sender, EventArgs e)
        {
            InitializeControls();
        }

        private void InitializeControls()
        {
            CmbRoles.Items.Clear();
            foreach (var role in _roleModels)
            {
                CmbRoles.Items.Add(new SelectItem(role.Name, role.Id));
            }
            CmbDepartments.Items.Clear();
            List<DepartmentDetailModel> departmentDetailModels = SetDepartmentList(_departmentModels);
            foreach (var dep in departmentDetailModels)
            {
                var si = new AntdUI.SelectItem(dep.Name, dep.Id) { };
                if (dep.DepartmentChild != null && dep.DepartmentChild.Count > 0)
                {
                    SetDepartmentSub(si, dep.DepartmentChild);
                }
                CmbDepartments.Items.Add(si);
            }
            if (_userModel.UserId == -1)
            {
                TxtUserName.Text = "";
                TxtNickName.Text = "";
                TxtPhone.Text = "";
                TxtPhone.Text = "";
                TxtEmail.Text = "";

                BtnSwitchGnder.SelectIndex = 0;
                BtnSwitchStatus.SelectIndex = 0;
            }
            else
            {
                TxtUserName.Text = _userModel.UserName;
                TxtNickName.Text = _userModel.NickName;
                TxtPhone.Text = _userModel.Phone;
                TxtEmail.Text = _userModel.Email;

                BtnSwitchGnder.SelectIndex = BtnSwitchGnder.Items.IndexOf(BtnSwitchGnder.Items.FirstOrDefault(i => int.Parse(i.ID) == _userModel.Gender));
                BtnSwitchStatus.SelectIndex = BtnSwitchStatus.Items.IndexOf(BtnSwitchStatus.Items.FirstOrDefault(i => int.Parse(i.ID) == _userModel.IsActive));

                // 设置权限选中
                List<object> roles = new List<object>();
                foreach (var role in _userModel.UserRoles)
                {
                    roles.Add(role.RoleId);
                }
                CmbRoles.SelectedValue = roles.ToArray(); 
                // 设置部门选中 
                CmbDepartments.SelectedValue = new SelectItem(_userModel.DepartmentName, _userModel.DepartmentId);

                // 头像
                if (!string.IsNullOrEmpty(_userModel.Gravatar) && File.Exists(_userModel.Gravatar))
                {
                    UploadAvatar.Image = Image.FromFile(_userModel.Gravatar);
                    UploadAvatar.ImageSvg = "Admin.CircularDeletion";
                }
            }
        }

        private void SetDepartmentSub(SelectItem si, List<DepartmentDetailModel> departmentList)
        {
            var subList = new List<AntdUI.SelectItem>();
            foreach (var model in departmentList)
            {
                var sis = new AntdUI.SelectItem(model.Name, model.Id) { };
                if (model.DepartmentChild != null && model.DepartmentChild.Count > 0)
                {
                    SetDepartmentSub(sis, model.DepartmentChild);
                }
                subList.Add(sis);
            }
            si.Sub = new List<object>();
            foreach (var sub in subList)
            {
                si.Sub.Add(sub);
            }
        }

        /// <summary>
        /// 构架部门树
        /// </summary>
        /// <param name="sourceModel"></param>
        /// <param name="parent"></param>
        public List<DepartmentDetailModel> SetDepartmentList(List<DepartmentDetailModel> sourceModel, int parent = 0)
        {
            List<DepartmentDetailModel> departmentModels = new List<DepartmentDetailModel>();
            List<DepartmentDetailModel> list = sourceModel.Where(s => s.ParentId == parent).ToList();
            foreach (var l in list)
            {
                departmentModels.Add(l);
                foreach (var dep in departmentModels)
                {
                    dep.DepartmentChild = GetChildren(sourceModel, dep.Id);
                }
            }
            return departmentModels;
        }
        /// <summary>
        /// 循环获取嵌套部门
        /// </summary>
        /// <param name="sourceModel"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<DepartmentDetailModel> GetChildren(List<DepartmentDetailModel> sourceModel, int parentId)
        {
            var children = sourceModel.Where(m => m.ParentId == parentId).ToList();
            foreach (var child in children)
            {
                child.DepartmentChild = GetChildren(sourceModel, child.Id);
            }
            return new List<DepartmentDetailModel>(children);
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void BtnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(TxtUserName.Text))
                {
                    AntdUI.Message.error(_form, "请输入用户名");
                    return;
                }

                // 获取到所有的roleId
                List<int> ids = new List<int>();
                foreach (var item in CmbRoles.SelectedValue)
                {
                    ids.Add((int)item);
                }

                // 如果新增的头像 需要保存在服务器
                if (!string.IsNullOrEmpty(_userModel.Gravatar))
                {
                    List<string> gravatarFileList = Directory.GetFiles(FilePath.GravatarFilePath).ToList();
                    if (!gravatarFileList.Contains(_userModel.Gravatar))
                    {
                        // 复制到服务器
                        string newFileName = Guid.NewGuid().ToString() + ".jpg";
                        File.Copy(_userModel.Gravatar, Path.Combine(FilePath.GravatarFilePath, newFileName), true);
                        _userModel.Gravatar = newFileName;
                    }
                    else
                    {
                        _userModel.Gravatar = new FileInfo(_userModel.Gravatar).Name;
                    }
                }

                _userModel.UserName = TxtUserName.Text;
                _userModel.Gender = int.Parse(BtnSwitchGnder.Items[BtnSwitchGnder.SelectIndex].ID);
                _userModel.NickName = TxtNickName.Text;
                _userModel.Phone = TxtPhone.Text;
                _userModel.Email = TxtEmail.Text;
                _userModel.IsActive = int.Parse(BtnSwitchStatus.Items[BtnSwitchStatus.SelectIndex].ID);

                UserEntity userEntity = _userModel.ToEntity();
                userEntity.DepartmentId = (int)CmbDepartments.SelectedValue;

                if (_userModel.UserId == -1)
                {
                    _userService.CreateUser(userEntity, ids);
                    _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"用戶管理新增：【{_userModel.UserIdAndUserName}】", "system:user:create");
                    AntdUI.Message.success(_form, "添加成功");
                }
                else
                {
                    userEntity.UserId = _userModel.UserId;
                    userEntity.CreateTime = _userModel.CreateTime;
                    _userService.UpdateUser(userEntity, ids);
                    _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"用戶管理新增：【{_userModel.UserIdAndUserName}】", "system:user:update");
                    AntdUI.Message.success(_form, "修改成功");
                }
                if (!string.IsNullOrEmpty(_userModel.Gravatar)) _userModel.Gravatar = FilePath.GravatarFilePath + _userModel.Gravatar;
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(_form, "修改用户失败：" + ex.Message);
            }
        }

        private void UploadAvatar_Click(object sender, EventArgs e)
        {
            if (UploadAvatar.ImageSvg == "Admin.Upload")
            {
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif|所有文件|*.*",
                    Title = "选择图片"
                };
                // 显示对话框并检查结果
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    _userModel.Gravatar = openFileDialog.FileName;
                    UploadAvatar.Image = Image.FromFile(_userModel.Gravatar);
                    UploadAvatar.ImageSvg = "Admin.CircularDeletion";
                }
            }
            else if (UploadAvatar.ImageSvg == "Admin.CircularDeletion")
            {
                _userModel.Gravatar = "";
                UploadAvatar.Image = null;
                UploadAvatar.ImageSvg = "Admin.Upload";
            }
        }
    }
}